package com.qf.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
//自定义网关过滤器
@Component
public class Filter1 implements GlobalFilter, Ordered {
    //编写这里需要的业务，请求进来会执行这些过滤器中的代码，执行后，请求才会被网关分发请求。
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("--------filter1---------");
        //1.获取请求中的token令牌（加密字符串）
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String token = request.getHeaders().getFirst("token");
        //2.判断如果获取不到token就认为没有权限访问，抛出异常
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //通过响应直接返回异常
            return response.setComplete();

        }
        //3.如果获取到就有权限，放行
        return chain.filter(exchange);




    }
//返回的数字，就是如果有多个过滤器，他们的执行顺序
    @Override
    public int getOrder() {


        return 0;
    }
}
